 var shoppingJson;
window.onload = function (){
    var customerJson = localStorage.getItem('customer');
   // change();
   // console.log(customerJson);
    if(customerJson == null || customerJson == undefined){
        alert('请登录后操作！');
        window.location.href = '/login/login.html';
    }else{
        var customer = JSON.parse(customerJson);
        console.log(customer);
        $("#custName").val(customer.custName);
        $("#custPhone").val(customer.custPhone);
        $("#address").val(customer.consigeeAddr);
        var url = "shoppingCart!getShoopingCart";
        //alert(customer.accountNo);
        var data = "accountNo=" + customer.accountNo;

        sendRequest("post",url,data,getShoppingCartBack);
    }
/**
 * @desc ：  get customers' shopping cart
 * @author : cirly
 * @param :
 * @return :  all the shopping cart infomation(List)
**/

     function getShoppingCartBack(result){
    console.log(typeof result);
    console.log(result);
         if(result ==  '"shoppingCart_null"' ){
             alert('您的购物车还没有商品，请添加商品后再试！');
             window.location.href = 'index.html';
         }else {
            // alert('123');
             var rs = eval("(" + result + ")");
             rs = JSON.parse(rs);
                 shoppingJson = rs;
                 show(rs);

         }
     }
     /**
      * @desc ： disdplay infomation to the page
      * @author : cirly
      * @param :  json of shopping cart
      * @return :
     **/
    function show(json){
        var str='<ul class="commodity_list_term">';
        for(var i = 0 ; i < json.length ; i++){
            str += '<li class="select">'+'<em aem="0" cart_id ="84" id="'+json[i].productQR+'" onclick="test(this)" ></em>'
                +'<img src=\"data:image/jpg;base64,'+ json[i].productPhoto+'">'
                +'<div class="div_center">'
                +'<h4>'+json[i].productName+'</h4>'
                +'<p class="now_value"><i>￥</i><b class="qu_su">'+json[i].salePrice+'</b></p></div>'
                +'<div class="div_right"> <i onclick="reducew(this)">-</i>'
                +'<span id='+"buyAcount_"+json[i].productQR+' class="zi">'+json[i].buyAmount+'</span>'
                +'<input id ='+json[i].productQR+' type="hidden" value="'+json[i].buyAmount+'">'
                +'<input id ='+json[i].productNumber+' type="hidden" value="'+json[i].productNumber+'">'
                +'<i onclick="plusw(this)">+</i>'
                +'</div>'
                +'</li>'
         // console.log(json[i].productNumber);
        }
        str+="</ul>";
        document.getElementById("shopping_list").innerHTML = str;
  // console.log(json);
    }


  }
  /**
   * @desc ：count the total price (a bad function name, burt it works)
   * @author : cirly
   * @param :
   * @return :
  **/

  function test(a){
         // alert("ffff");
          var su = $(a).attr("aem");
          var carts_id=$(a).attr("cart_id");
          var totalH = $("#total_price b").text(); /* 合计金额  */
          if(su == 0){
              /* 单选商品  */
              if($(a).hasClass("pitch_on")){
                  /*去该店全选*/
                  $(a).parents("ul").siblings(".select").find("em").removeClass("pitch_on");
                  /*去底部全选*/
                  $("#all_pitch_on").removeClass("pitch_on");
                  $(a).removeClass("pitch_on");
                  reduceMod($(a),totalH);
                  cart_id[carts_id]="";
                  delete cart_id[carts_id];
              }else{
                  $(a).addClass("pitch_on");
                  var n = $(a).parents("ul").children().find(".pitch_on");
                  var n1 = $(a).parents("ul").children();
                  plusMod($(a),totalH,0,noX);
                  cart_id[carts_id]="";
                  /*该店商品全选中时*/
                  if(n.length == n1.length){
                      $(a).parents("ul").siblings(".select").find("em").addClass("pitch_on");
                  }
                  /*商品全部选中时*/
                  var fot = $(".commodity_list_box .tite_tim .pitch_on");
                  var fot1 = $(".commodity_list_box .tite_tim em");
                  if(fot.length == fot1.length)
                      $("#all_pitch_on").addClass("pitch_on");
              }
          }else{
              /* 全选该店铺  */
              if($(a).hasClass("pitch_on")){
                  /*去底部全选*/
                  $("#all_pitch_on").removeClass("pitch_on");
                  $(a).removeClass("pitch_on");

                  commodityReduceMod($(a),totalH);
                  $(a).parent().siblings("ul").find("em").removeClass("pitch_on");
                  delete cart_id[carts_id];
              }else{
                  commodityReduceMod($(this),totalH);

                  $(a).addClass("pitch_on");

                  $(a).parent().siblings("ul").find("em").addClass("pitch_on");

                  if(plus != NaN && plus != undefined){
                      totalH = parseFloat(totalH)-parseFloat(plus);
                  }
                  commodityPlusMod($(a),totalH);
                  cart_id[carts_id]="";
                  /*商品全部选中时*/
                  var fot = $(".commodity_list_box .tite_tim .pitch_on");
                  var fot1 = $(".commodity_list_box .tite_tim em");
                  if(fot.length == fot1.length)
                      $("#all_pitch_on").addClass("pitch_on");

              }
          }

          //计算选择数值
          number();

  }
    /**
    * @desc ：user payment (default:payed)
    * @author : cirly
    * @param :
    * @return :
     **/
  function account(){
        /**
         * 为了赶进度，变量定义的及其放荡不羁
         * 逻辑结构也是天马行空，有优化的空间，看到的同学不要怪我这个沙雕，因为我比较垃圾...
         */





       if($("#total_price b").text() == 0){
           alert("请选择要购买的商品！");
           return ;
        }else {
           if (confirm("你确定结算吗？")) {
              // var customer = JSON.parse(customerJson);


               // alert("点击了确定");
               var product = [];          //商品信息
               var buyNumber = [];        //价格信息
               var temp = [];             //存放购物信息对象（phone,No,QR,amount,price）
               var emlist = document.getElementsByTagName('em');

               for (var i = 0; i < emlist.length; i++) {
                   if (emlist[i].className == 'pitch_on') {
                       var id = emlist[i].getAttribute("id");
                       product.push(id);
                       //console.log($("#id").next().attr('src'));
                       //emlist[i].parentNode.childNodes[1].src;
                       buyNumber.push($(emlist[i]).parent().find(".zi").eq(0).text());
                   }
               }
                         for (var i = 0; i < product.length; i++) {
                             for (var j = 0; j < shoppingJson.length; j++) {
                                 if (product[i] == shoppingJson[j].productQR) {
                                     var buyInfo = new Object();
                                     buyInfo.custPhone = shoppingJson[j].custPhone;
                                     buyInfo.accountNo = shoppingJson[j].accountNo;
                                     buyInfo.productQR = shoppingJson[j].productQR;
                                     buyInfo.productName = shoppingJson[j].productName;
                                     buyInfo.salePrice = shoppingJson[j].salePrice;
                                     buyInfo.buyAmount = buyNumber[i];
                                     buyInfo.productPhoto = shoppingJson[j].productPhoto;
                                     buyInfo.productColor = shoppingJson[j].productColor;
                                     buyInfo.buyPrice = $("#total_price b").text();
                                     temp.push(buyInfo);
                                 }
                             }
                         }
                         var list = new Array();
                         for (var i = 0; i < temp.length; i++) {
                             list.push(temp[i])
                         }
               localStorage.setItem('proInfo',JSON.stringify(list));
              window.location.href = 'cart_index.html';


                     }
                     else {
                         //alert("点击了取消");
                     }

       }
  }


 //加
 function plusw(obj){

     var $this = $(obj);
    //alert("123");

     var totalH = $("#total_price b").text(); /* 合计金额  */
     var ise = $this.siblings("span").text();
     var gc_id = $this.siblings("input").val();
     var n =parseInt(ise)+1;                   //点击加号之后的数量
     var productNumber = parseInt($this.parent().children("input").get(1).value);        //商品库存
     if(n > productNumber){
         alert("库存仅剩"+productNumber+"件，请修改购买数量！");
     }else{
     //console.log(productNumber);
     noX++;


     $this.siblings("span").text(n);
     if($this.parent().parent().children("em").hasClass("pitch_on")){
         var mo = $this.parent().parent().children("em");
         plusMod(mo,totalH,2,noX);
         noX=0;
     }
     var url = "shoppingCart!updateShopping";
     //var number = parseInt($this.parent().children("input").get(0).value)+1;
     var data = "productQR=" + $this.parent().children("input").get(0).getAttribute('id')+
         "&buyAmount="+n;
     console.log(data);
     sendRequest("post",url,data,updateBack);
     }
     //goods_count_adjust(gc_id,n,null);
 }

 function updateBack(result){
    console.log(result);
 }


 //删除
 function big_cart_remove(){
     var qrList = [] ;
     // alert(	$(".commodity_list_term .pitch_on").getAttribute('id'));
     var emlist = document.getElementsByTagName('em');
     for(var i = 0 ;i < emlist.length ; i ++ ){
         if(emlist[i].className == 'pitch_on'){
             qrList.push(emlist[i].getAttribute("id"));
         }
     }
     $.ajax({
         url: 'shoppingCart!deleteCart',
         data: {'qrList': JSON.stringify(qrList)},
         cache: false,
         async: false,
         traditional: true,
         type: "POST",
         dataType: 'json',
         /*    success: function (data) {
                 // alert("添加成功！");
                 if (data == 'delete_success') {
                     alert("！");
                     window.location.href = 'shoppingCart.html';
                     //        // layer.msg(data.content, {icon: 6});
                 } else {
                     alert("购买失败！");
                     //         //layer.msg(data.content, {icon: 1});
                 }
             }
         })*/
     })
     // $(".commodity_list_term .pitch_on").length;
     $(".commodity_list_term .pitch_on").parent().remove();
     $(".commodity_list .tite_tim > em.pitch_on").parents(".commodity_box").remove();
 }

 var noX = 0;  /* 没选中时点击加减计算数量  */
 var allThis = $(".commodity_box .select em"); /*底部全选*/
 /* 减  */
 function reduceMod(e,totalH,mod,noX){
     var tn = e.siblings().find(".qu_su").text(); /* 当前选中商品  */
     var tn1 = e.siblings().find(".zi").text(); /* 商品数量  */
     if(mod != 2){
         var Total = parseFloat(totalH) - (tn*tn1);	/* 总价格减该商品总数价格  */
         $("#total_price b").text(Total.toFixed(2));
     }else{
         /* 合计加单价-1 */
         var Total = parseFloat(totalH) - parseFloat(tn);	/* 总价格减该商品总数价格  */
         $("#total_price b").text(Total.toFixed(2));
     }

 };
 /* 加  */
 function plusMod(e,totalH,mod){
     var tn = e.siblings().find(".qu_su").text(); /* 当前选中商品  */
     var tn1 = e.siblings().find(".zi").text(); /* 商品数量  */
     if(mod != 2){
         var Total = parseFloat(totalH)+(tn*tn1);	/* 总价格加上该商品总数价格  */
         $("#total_price b").text(Total.toFixed(2));
     }else{
         /* 合计加单价+1 */
         var Total = parseFloat(totalH)+(parseFloat(tn)+(noX-1));	/* 总价格加上该商品总数价格  */
         $("#total_price b").text(Total.toFixed(2));
     }

 };
 /*全选该店商品价格 加*/
 function commodityPlusMod(e,totalH){
     var qu = e.parents(".commodity_list").find(".pitch_on").parent().find(".qu_su");
     var quj = e.parents(".commodity_list").find(".pitch_on").parent().find(".zi");
     var Total = 0;
     var erTotal = true;
     /* 该商品全部金额  */
     for(var i=0; i<qu.length; i++)
     {
         var n = qu.eq(i).text();
         var n1 = quj.eq(i).text();
         /*合计价格*/
         if(erTotal){
             Total = parseFloat(totalH) +(parseFloat(n)*parseFloat(n1));
             if(Total < 0)
                 Total=0;
             erTotal = false;
         }else{
             Total = parseFloat(Total) + (parseFloat(n)*parseFloat(n1));
             if(Total < 0)
                 Total=0;
         }
     }
     $("#total_price b").text(Total.toFixed(2)); /* 合计金额  */
 };


 var plus;
 /*全选该店商品价格 减*/
 function commodityReduceMod(e,totalH){
     var qu = e.parents(".commodity_list").find(".pitch_on").parent().find(".qu_su");
     var quj = e.parents(".commodity_list").find(".pitch_on").parent().find(".zi");
     var Total = 0;

     var erTotal = true;
     /* 该商品全部金额  */
     for(var i=0; i<qu.length; i++)
     {
         var n = qu.eq(i).text();
         var n1 = quj.eq(i).text();
         /*合计价格*/
         if(erTotal){
             Total = parseFloat(totalH) - (parseFloat(n)*parseFloat(n1));
             plus = parseFloat(n)*parseFloat(n1);
             if(Total < 0)
                 Total=0;
             erTotal = false;
         }else{
             Total = parseFloat(Total) - (parseFloat(n)*parseFloat(n1));
             plus = parseFloat(n)*parseFloat(n1);
             if(Total < 0)
                 Total=0;
         }

         $("#total_price b").text(Total.toFixed(2)); /* 合计金额  */
     }

     return plus;
 };

 var bot = 0;
 $("#all_pitch_on").click(function(){
     if(bot == 0){
         $(this).addClass("pitch_on");
         allThis.removeClass("pitch_on");
         allThis.addClass("pitch_on");
         /*总价格*/
         commodityWhole();
         bot = 1;
         //重新加入属性对象
         for(var key in cart_id_copy){
             cart_id[key]="";
         }
     }else{
         $(this).removeClass("pitch_on");
         allThis.removeClass("pitch_on");
         $("#total_price b").text("0");
         bot = 0;
         //移除全部对象
         for(var key in cart_id){
             delete cart_id[key];
         }
     }
     //计算选择数值
     number();
 });

 function number() {
     var num=0;
     for(var key in cart_id){
         num++;
     }
     //将选择的放入到计算里面
     //$("#confirm_cart").html("结算("+num+")");
 }

 /* 编辑商品  */
 var topb = 0;
 $("#rem_s").click(function(){
     if(topb == 0){
         $(this).text("完成");
         $(".total_amount").hide(); /* 合计  */
         $("#confirm_cart").hide(); /* 结算  */
         $("#confirm_cart1").show(); /* 删除 */
         topb = 1;
     }else{
         topb = 0;
         $(this).text("编辑");
         $(".total_amount").show(); /* 合计  */
         $("#confirm_cart").show(); /* 结算  */
         $("#confirm_cart1").hide(); /* 删除 */
         allThis.removeClass("pitch_on"); /* 取消所有选择  */
         $("#all_pitch_on").removeClass("pitch_on"); /* 取消所有选择  */
         $("#total_price b").text("0"); /*合计价格清零*/

     }

 });

 /* 加减  */

 function reducew(obj){
     //减
     var $this = $(obj);
     var totalH = $("#total_price b").text(); /* 合计金额  */
     var ise = $this.siblings("span").text();
     var gc_id = $this.siblings("input").val();
     if(noX <= 0){
         noX = 0;
     }else{
         noX--;
     };

     if(parseInt(ise) <= 1){
         $this.siblings("span").text("1");
     }else{
         var n =parseInt(ise)-1;
         $this.siblings("span").text(n);
         if($this.parent().parent().children("em").hasClass("pitch_on")){
             var mo = $this.parent().parent().children("em");
             reduceMod(mo,totalH,2,noX);
             noX=0;
         }

     }
     var url = "shoppingCart!updateShopping";
     var number = parseInt($this.parent().children("input").get(0).value)+1;
     var data = "productQR=" + $this.parent().children("input").get(0).getAttribute('id')+
         "&buyAmount="+n;
     console.log(data);
     sendRequest("post",url,data,updateBack);

     //goods_count_adjust(gc_id,n,null);
 };
